//
//  CZSQLiteManager.swift
//  GZWeibo009
//
//  Created by gzxzmac on 16/4/6.
//  Copyright © 2016年 gzxzmac. All rights reserved.
//

import UIKit

import FMDB

/*
    数据库操作:
        1.打开数据库
        2.创建表
        3.操作数据
*/

class CZSQLiteManager: NSObject {

    static let sharedManager = CZSQLiteManager()
    
    var dbQueue: FMDatabaseQueue
    
    private override init() {
        let dbPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/status.db")
        print("dbPath: \(dbPath)")
        
        // 如果数据不存在会创建,并打开
        dbQueue = FMDatabaseQueue(path: dbPath)
        super.init()
        
        createTable()
    }
    
    private func createTable() {
        // 读取sql
        let tablesPath = NSBundle.mainBundle().pathForResource("tables.sql", ofType: nil)!
        
        let sqls = try! String(contentsOfFile: tablesPath)
        
        // 执行sql
        dbQueue.inTransaction { (db, rollback) -> Void in
            if db.executeStatements(sqls) {
                print("创建表成功")
            } else {
                print("创建表失败")
            }
            
        }
    }
}
